#version 430 core

uniform sampler2D DepthTex;

uniform vec4 Ambient;

uniform vec3 LightColor;
uniform vec3 LightPosition;

uniform vec3 EyeDirection;

in vec4 Color;
in vec3 Normal;
in vec4 Pos;
in vec4 ShadowCoord;

out vec4 FragColor;

void main()
{
    // 光线方向向量 = normalize(光源的位置 - 片元的位置)
    vec3 lightDirection = LightPosition - vec3(Pos.xyz);
    float lightDistance = length(lightDirection);
    lightDirection = lightDirection / lightDistance;

    vec3 halfVector = normalize(lightDirection + EyeDirection);
    
    float diffuse = max(0.0f, dot(Normal, lightDirection));
    float specular = max(0.0f, dot(Normal, halfVector));

    if (diffuse <= 0.00001)
        specular = 0.0f;

	vec3 shadow = ShadowCoord.xyz / ShadowCoord.w; // 齐次空间坐标转换
	float d = texture(DepthTex, shadow.xy).r; // 读取深度纹理中的深度值
	float f = 0.0;
	if (shadow.z <= d) // 当前片元在 Light 视角下的深度值小于等于深度纹理中的值，该片元没有被遮挡
	{
		f = 1.0;
	}
	
    vec3 scatteredLight = vec3(Ambient) + LightColor * diffuse * f;
    vec3 reflectedLight = LightColor * specular * f;

    vec3 rgb = min(Color.rgb * scatteredLight + reflectedLight, vec3(1.0));
    FragColor = vec4(rgb, Color.a);
}